﻿@{
    ViewBag.Title = "Store";
    Layout = "~/Views/Shared/_Layout_Administration.cshtml";
}
@section head
{
    <link href="/Content/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
}


@*<div class="row">
    <div class="span4">
        <ul class="container empty-item" data-bind="sortableList: { tmpl: 'newSitePageDefinitionTmpl', list: newSitePageDefinition }">
        </ul>
    </div>
    <div class="span4">
        <div class="alert alert-info">
            Drag this to categories to create category.           
        </div>
    </div>
</div>*@

<div id="main">

    <div id="selected-category" class="padding-bottom-10 row hide">
        <div class="span0 back-to-parent">
            <i data-bind="click: function() { self.backToParentCategory(); }" class="icon-circle-arrow-left pointer"></i>
        </div>
        <div class="span9">
            <h1 data-bind="text: self.selectedCategory.Name"></h1>
        </div>
    </div>

    <h2>Categories:</h2>

    <div class="preloader preloader-store-categories hide"></div>
    <table class="table-striped">
        <thead>
            <tr>
                <th><span class="btn btn-primary add-category" data-bind="click: addCategory"><span>+</span></span>
                </th>
                <th>Name
                </th>
                <th>Img
                </th>
                <th>FriendlyUrl
                </th>
                <th>ProductsCount
                </th>
                <th>IsEnabled
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody class="unstyled store-categories " data-bind="foreach: storeCategories">
            <tr>
                <td><i data-bind="click: $parent.removeCategory" class="icon-remove pointer remove-item"></i></td>
                <td><a href="#" data-bind="text: Name, click: function() { self.selectCategory($data); }"></a></td>
                <td>
                    <img src="#" data-bind="attr: { src: SmallImgLink}" />
                </td>
                <td data-bind="text: FriendlyUrl"></td>
                <td data-bind="text: ProductsCount"></td>
                <td data-bind="text: IsEnabled"></td>
                <td>
                    <i data-bind="click: function() { self.openCategoryEditDialog($data); }" class="icon-edit pointer"></i>
                </td>
            </tr>
        </tbody>
    </table>
    <br />

    <div class="store-products-headers hide">
        <hr class="soften">
        <h2>Products:</h2>
    </div>
    <div class="preloader preloader-store-products hide"></div>
    <table class="table-striped">
        <thead class="store-products-headers hide">
            <tr>
                <th>Id
                </th>
                <th>ArtNo
                </th>
                <th>Name
                </th>
                <th>Description
                </th>
                <th>Cost
                </th>
            </tr>
        </thead>
        <tbody class="unstyled store-products" data-bind="foreach: storeProducts">
            <tr>
                <td data-bind="text: Id"></td>
                <td data-bind="text: ArtNo"></td>
                <td data-bind="text: Name"></td>
                <td data-bind="text: Description"></td>
                <td data-bind="text: Cost"></td>
                <td><a data-bind="click: function() { self.editProduct($data); }" href="#">Edit</a></td>
                <td><a data-bind="click: function() { self.deleteProduct($data); }" href="#">Delete</a></td>
            </tr>            
        </tbody>
        <tfoot>
           <tr>
                <td><a data-bind="click: function() { self.addProduct(); }" href="#">Add</a></td>
            </tr>
        </tfoot>
    </table>

</div>

@* modal dialof *@
<div id="dialogEditModal" class="fade modal" style="display: none;">
    <div class="modal-header">
        <a href="#" class="close" data-bind="click: self.closeEditDialog">&times;</a>
        <h3>Category details editing</h3>
    </div>
    <div class="modal-body">
        <div class="divDialogElements">
            <div class="modal-editing">
                <table class="hide-on-cb-showing">
                    <tr>
                        <td colspan="2">
                            <div style="position: relative;" id="pnlUpload">
                                <input type="button" id="btnUpload" value="Upload Image" />
                                <div style="position: absolute; top: 4px; left: 3px;">
                                    <input id="fuFileUploader" name="file_upload" type="file" />
                                </div>
                            </div>
                            <div>
                                <div id="pnlUploadedImage" style="display: none">
                                    <h2>Uploaded image</h2>
                                    @*<input type="button" id="btnCrop" onclick="javascript: cropImage();" value="Crop Image" />
                                    <input type="button" id="btnResize" onclick="javascript: resizeImage();" value="Resize Image" />*@
                                    <label id="lblMethodError" style="display: none"></label>
                                    <br />
                                    <img src="#" class="image-picker-upoloaded-image" id="imgUploadedImage" alt="Uploaded Image" />
                                </div>
                                @*<div id="pnlNewImage" style="display: none">
                                    <h2>Modified image</h2>
                                    <img src="#" id="imgNewImage" alt="Image" />
                                </div>*@
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>Image:</td>
                        <td class="intr-descr-2-col">
                            <input type="text" placeholder="Type smth…" data-bind="value: self.editingCategory.FullImgLink()" />
                        </td>
                    </tr>
                    <tr>
                        <td>Name:</td>
                        <td class="intr-descr-2-col">
                            <input type="text" placeholder="Type smth…" data-bind="value: self.editingCategory.Name()" />
                        </td>
                    </tr>
                    <tr>
                        <td>Friendly url:</td>
                        <td class="intr-descr-2-col">
                            <input type="text" placeholder="Type smth…" data-bind="value: self.editingCategory.FriendlyUrl()" />
                        </td>
                    </tr>
                    <tr>
                        <td>Is enabled:</td>
                        <td class="intr-descr-2-col">
                            <input type="checkbox" data-bind="checked: self.editingCategory.IsEnabled()" />
                        </td>
                    </tr>
                </table>
            </div>

        </div>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn primary" data-bind="click: self.saveCategory">Save</a>
        <a href="#" class="btn secondary" data-bind="click: self.closeEditDialog">Cancel</a>
    </div>



</div>



@section scripts{

    <script src="/Scripts/Uploadify/swfobject.js" type="text/javascript"></script>
    <script src="/Scripts/Uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.Jcrop.min.js" type="text/javascript"></script>

    <script type="text/javascript">

        var initCategoryId = '@ViewBag.InitCategoryId';

        function StoreCategory(data) {
            this.Id = ko.observable(data.Id);
            this.FullImgLink = ko.observable(data.FullImgLink);
            if (data.SmallImgLink != null) {
                this.SmallImgLink = ko.observable(data.SmallImgLink);
            }
            else {
                this.SmallImgLink = ko.observable("/Content/cross_icon.jpg");
            }
            this.SortOrder = ko.observable(data.SortOrder);
            this.IsEnabled = ko.observable(data.IsEnabled);
            this.ProductsCount = ko.observable(data.ProductsCount);
            this.FriendlyUrl = ko.observable(data.FriendlyUrl);
            this.Name = ko.observable(data.Name);
            this.IsNewImage = false;
        }

        function StoreProduct(data) {
            this.Id = ko.observable(data.Id);
            this.ArtNo = ko.observable(data.ArtNo);
            this.Name = ko.observable(data.Name);
            this.Description = ko.observable(data.Description);
            this.Cost = ko.observable(data.Cost);
        }

        function FillObjectProperties(object) {
            object.Id = ko.observable();
            object.Name = ko.observable();
            object.FriendlyUrl = ko.observable();
            object.SmallImgLink = ko.observable();
            object.FullImgLink = ko.observable();
            object.IsEnabled = ko.observable();
        }

        categoryNavIds = new Object();
        categoryNavIds.ParentId = 0;
        categoryNavIds.CurrentId = 0;

        function CategoryNavDeeper(selectedCategoryId) {
            categoryNavIds.ParentId = categoryNavIds.CurrentId;
            categoryNavIds.CurrentId = selectedCategoryId;
        }

        function CategoryNavUpper() {

            categoryNavIds.CurrentId = categoryNavIds.ParentId;
        }

        var self;

        function StoreCategoryListViewModel() {

            self = this;



            self.storeCategories = ko.observableArray([]);
            self.storeProducts = ko.observableArray([]);

            self.storeEditingCategories = ko.observableArray([]);

            self.editingCategory = new Object;// = ko.observable(); <= fuck yee
            self.selectedCategory = new Object;

            FillObjectProperties(self.editingCategory);
            FillObjectProperties(self.selectedCategory);

            self.removeCategory = function (storeCategory) {
                self.storeCategories.remove(storeCategory);
            };

            self.addCategory = function () {

            };

            self.selectCategory = function (category) {
                var id = category.Id();
                self.selectCategoryById(id, category.Name());
            }

            self.selectCategoryById = function (id, name) {              
               
                self.loadDataFromServerCategories(id);
                if (id != 0) {
                    self.loadDataFromServerProducts(id);
                }
                self.selectedCategory.Id(id);              
                self.selectedCategory.Name(name);
                CategoryNavDeeper(id);
                self.ToggleSelectedCategory();
               
            }

            self.setEditingCategoryImg = function (url) {

                self.editingCategory.FullImgLink(url);
                self.editingCategory.IsNewImage = true;

            }

            self.editProduct = function (product) {
                var id = product.Id();
                window.location.href = "Store/EditProduct?id=" + id;
                return false;
            }

            self.deleteProduct = function (product) {
                if (confirm("Are you sure you want to delete?")) {
                    var id = product.Id();

                    $.ajax({
                        url: "Store/DeleteProduct?id=" + id
                    }).done(function (result) {
                        alert(result);
                        if (result == 'OK') {
                            self.storeProducts.remove(product);
                        }
                    });
                }
                return false;
            }

            self.addProduct = function (product) {

                $.getJSON("Store/AddProduct?categoryId=" + self.selectedCategory.Id(), function (data) {
                   
                    var newProduct = new StoreProduct(data);
                    self.storeProducts.push(newProduct)

                });

               // window.location.href = "Store/EditProduct?id=0&categoryId=" + self.selectedCategory.Id();
                return false;
            }

            self.backToParentCategory = function () {
                self.loadDataFromServerCategories(categoryNavIds.ParentId);
                self.loadDataFromServerProducts(categoryNavIds.ParentId);
                CategoryNavUpper();
                self.ToggleSelectedCategory();
            }

            self.ToggleSelectedCategory = function () {
                var selectedCategoryDiv = $('#selected-category');

                if (categoryNavIds.CurrentId == 0 && !selectedCategoryDiv.hasClass('hide')) {
                    selectedCategoryDiv.addClass('hide');
                }
                else if (categoryNavIds.CurrentId != 0 && selectedCategoryDiv.hasClass('hide')) {
                    selectedCategoryDiv.removeClass('hide');
                }
            }

            self.openCategoryEditDialog = function (category) {

                self.editingCategory.Id(category.Id);
                self.editingCategory.Name(category.Name);
                self.editingCategory.FriendlyUrl(category.FriendlyUrl);
                self.editingCategory.FullImgLink(category.FullImgLink);
                self.editingCategory.SmallImgLink(category.SmallImgLink);
                self.editingCategory.IsEnabled(category.IsEnabled);
                //var mappedCategory = $.map(category, function (item) { return new StoreCategory(item) });
                //self.editingCategory(mappedCategory);

                var modalDialog = $("#dialogEditModal");

                var browserName = navigator.appName;
                if (browserName == 'Microsoft Internet Explorer' && modalDialog.hasClass("fade")) {
                    modalDialog.removeClass("fade");
                }

                modalDialog.modal({ show: true });
            }

            self.closeEditDialog = function () {
                $("#dialogEditModal").modal('hide');
                return false;
            };

            self.loadDataFromServerProducts = function (id) {
                TogglePreloader('.preloader-store-products', '.store-products');
                $.getJSON("GetStoreProducts?categoryId=" + id, function (allData) {
                    var mappedStoreProducts = $.map(allData, function (item) { return new StoreProduct(item) });
                    self.storeProducts(mappedStoreProducts);
                    TogglePreloader('.preloader-store-products', '.store-products');
                    var productsHeaders = $(".store-products-headers");
                    if (self.selectedCategory.Name != '' && productsHeaders.hasClass('hide')) {
                        productsHeaders.removeClass('hide');
                    }
                    else if (self.storeProducts.length == 0 && !productsHeaders.hasClass('hide')) {
                        productsHeaders.addClass('hide');
                    }
                    else if (self.selectedCategory.Name == '' && !productsHeaders.hasClass('hide')) {
                        productsHeaders.addClass('hide');
                    }
                });
            };

            self.loadDataFromServerCategories = function (id) {
                TogglePreloader('.preloader-store-categories', '.store-categories');
                $.getJSON("GetStoreCategories?categoryId=" + id, function (allData) {
                    var mappedStoreCategories = $.map(allData, function (item) { return new StoreCategory(item) });
                    self.storeCategories(mappedStoreCategories);
                    TogglePreloader('.preloader-store-categories', '.store-categories');
                });
            };

            self.saveCategory = function () {

                self.storeEditingCategories.push(self.editingCategory);

                if (!HasErrors()) {
                    $.ajax("SetCategory", {
                        data: ko.toJSON(self.editingCategory),
                        type: "post", contentType: "application/json",
                        success: function (result) { alert(result); }
                    });
                }
            };

            self.selectCategoryById(initCategoryId)

            // self.loadDataFromServerCategories(categoryNavIds.ParentId);
        }

        ko.applyBindings(new StoreCategoryListViewModel());
    </script>


    <script type="text/javascript">
        var x = 0, y = 0, w = 0, h = 0;
        var imageHandler = "/ImageHandler.ashx?id=";

        var jCropAPI;

        $(function () {
            // Uploadify File Upload System
            // SessionSync data is sent in scriptData for security reasons, see UploadifySessionSync() in global.asax
            var UploadifyAuthCookie = '@(Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)';
            var UploadifySessionId = '@(Session.SessionID)';

            $("#fuFileUploader").uploadify({
                'hideButton': true,       // We use a trick below to overlay a fake html upload button with this hidden flash button                         
                'wmode': 'transparent',
                'uploader': '@(Url.Content("/Scripts/Uploadify/uploadify.swf"))',
                'cancelImg': '@(Url.Content("/Scripts/Uploadify/cancel.png"))',
                'buttonText': 'Upload Image',
                'script': '/Media/FileUpload',
                'multi': true,
                'auto': true,
                'fileExt': '*.jpg;*.gif;*.png;*.jpeg',
                'fileDesc': 'Image Files',
                'scriptData': { RequireUploadifySessionSync: true, SecurityToken: UploadifyAuthCookie, SessionId: UploadifySessionId },
                'onComplete': function (event, ID, fileObj, response, data) {
                    response = $.parseJSON(response);
                    if (response.Status == 'OK') {

                        // $("#pnlUpload").hide();
                        $("#pnlUploadedImage").show();
                        $("#imgUploadedImage").attr("src", imageHandler + response.Id);

                        self.setEditingCategoryImg(imageHandler + response.Id);

                        //$('#imgUploadedImage').Jcrop({                           
                        //    boxHeight: 300,
                        //    //boxWidth: 200,
                        //    onChange: setCoords,
                        //    onSelect: setCoords,

                        //    //minSize: [200, 200]
                        //    //maxSize: [200, 200]
                        //}, function () { jCropAPI = this; });                       

                    }
                }
            });
        });

        function setCoords(c) {
            x = c.x;
            y = c.y;
            w = c.w;
            h = c.h;
        };

        function cropImage() {

            var i_h = $("#imgUploadedImage").height();
            var i_w = $("#imgUploadedImage").width();

            $.ajax({
                url: "/Media/CropImage",
                type: "POST",
                data: { i_h: i_h, i_w: i_w, x: x, y: y, w: w, h: h },
                success: function (data) {
                    $('#lblMethodError').hide();
                    $("#pnlNewImage").show();
                    jCropAPI.destroy();
                    $('#imgUploadedImage').Jcrop({
                        boxHeight: 300,
                        boxWidth: 500,
                        onChange: setCoords,
                        onSelect: setCoords//,
                        //minSize: [200, 200]
                        //maxSize: [200, 200]
                    }, function () { jCropAPI = this; });
                },
                error: function (xhr, status, error) {
                    // Show the error
                    $('#lblMethodError').text(xhr.responseText);
                    $('#lblMethodError').show();
                }
            });

        }

        function resizeImage() {
            // Call the server side function to resize the image
            $.ajax({
                url: "/Media/ResizeImage",
                type: "POST",
                success: function (data) {
                    $('#lblMethodError').hide();
                    $("#pnlNewImage").show();
                    $("#imgNewImage").attr("src", imageHandler + data);
                },
                error: function (xhr, status, error) {
                    // Show the error
                    $('#lblMethodError').text(xhr.responseText);
                    $('#lblMethodError').show();
                }
            });
        }
    </script>

}